package com.web.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.web.annotation.LoginRequired;
import com.web.entity.UserInfo;
import com.web.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.RuntimeSqlException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

/**
 * Created by xukk on 2017/7/18.
 */
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService service;
    @Autowired
    public StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解，不需要认证
        if (methodAnnotation == null) {
            // 执行认证
            String token = request.getHeader("token");  // 从 http 请求头中取出 token
            if (token == null) {
                throw new ServiceException("请求头缺少必要参数!");
            }
            String userId;
            try {
                userId = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException e) {
                throw new ServiceException("TOKEN已经失效，请重新登录获取");
            }
            UserInfo user = service.info("user_id",String.valueOf(userId));
            if (user == null) {
                throw new ServiceException("请到注册页面注册，谢谢配合🙏");
            }
            String  RToken = redisTemplate.opsForValue().get("TOKEN:"+userId);
            if(StringUtils.isBlank(RToken)){//redis里的token过期了
                throw new ServiceException("TOKEN不存在，请重新登录获取");
            }
            if(!RToken.equals(token)){
                throw new ServiceException("您的账号已在其他设备登录，请注意密码的保密措施!");
            }
            // 验证 token
            try {
                JWTVerifier verifier =  JWT.require(Algorithm.HMAC256(userId+"")).build();
                try {
                    verifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new ServiceException("TOKEN已经失效，请重新登录获取");
                }
            } catch (UnsupportedEncodingException ignore) {}
            request.setAttribute("userInfo", userId);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }

}